package xyz.labmem.main.tool;

import cn.hutool.core.util.StrUtil;
import cn.hutool.setting.Setting;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import xyz.labmem.main.error.FuncException;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;

@Slf4j
public class NetUtil extends cn.hutool.core.net.NetUtil {

    private static String path = null;

    /**
     * 获取ip地址
     *
     * @return ip
     */
    public static String getIpAddr() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        assert request != null;
        String ipAddress = request.getHeader("Proxy-Client-ipCode");
        try {
            if (ipAddress != null && ipAddress.length() > 0 && !"unknown".equalsIgnoreCase(ipAddress)) {
                return ipAddress;
            }

            ipAddress = request.getHeader("x-forwarded-for");

            if (ipAddress != null && ipAddress.length() > 0 && !"unknown".equalsIgnoreCase(ipAddress)) {
                int index = ipAddress.indexOf(",");
                if (index > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
                return ipAddress;
            }
            ipAddress = request.getRemoteAddr();
            if ("127.0.0.1".equals(ipAddress) || "0:0:0:0:0:0:0:1".equals(ipAddress)) {
                ipAddress = InetAddress.getLocalHost().getHostAddress();
            }
        } catch (Exception e) {
            throw new FuncException("获取ip地址错误", e);
        }
        return ipAddress;

    }

    /**
     * 获取服务器访问地址
     *
     * @return
     */
    public static String getServerAddr() {
        if (path != null)
            return path;
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
    }

    /**
     * 获取浏览器信息
     *
     * @return
     */
    public static String getBrowserInfo() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();
        return request.getHeader("User-Agent");
    }

}
